<template>
    
    <!--    第一行导航栏-->
    <div class="navigation-bar">
        <div class="base navigation-bar-context">
            <div class="cloud-info">
                <!--                网易云图片-->
                <van-image
                    width="50"
                    height="50"
                    lazy-load
                    round
                    :src="ImageUrl"
                    @click="getRouterToHome"
                />
                <div class="cloud-info-text" @click="getRouterToHome">
                    网易云音乐
                </div>
            </div>
            <div class="bar-context" v-for="(key, value) in barDataList.firstBarNameAndUrl"
                 @click="getRouterToOther(key, value)"
                 :key="value" :class="{'bar-context-bg-active': isActiveBar(value)}">
                <div>
                    {{ value }}
                    <div class="bottom-triangle" v-show="isActiveBar(value)">
                    </div>
                </div>
            </div>
            <div class="bar-search">
                <!--                <van-search-->
                <!--                    v-model:value="searchValue"-->
                <!--                    shape="round"-->
                <!--                    background="#242424"-->
                <!--                    placeholder="音乐/视频/电台/用户"-->
                <!--                    @search="doSearch"-->
                <!--                />-->
                <n-dropdown @select="handleSelect" trigger="hover" :options="options">
                    <n-input v-model:value="searchValue" type="text" placeholder="音乐/视频/电台/用户" round clearable
                             :on-input="inputChange" @keyup.enter="getRouterToSearchValue(searchValue)"/>
                </n-dropdown>
            </div>
            <div class="creators-center">
                创作者中心
            </div>
            <div class="user-icon">
                <div v-show="store.state.user.isLogin">
                    <n-tooltip trigger="hover">
                        <template #trigger>
                            <n-badge value="9">
                                <n-avatar
                                    circle
                                    size="medium"
                                    :src="store.state.user.avatarUrl"/>
                            </n-badge>
                        </template>
                        <p class="cursor-pointer hover:text-red-600 my-2"
                           @click="getRouterToUserHome(store.state.user.uid)">
                            个人首页
                        </p>
                        <p class="cursor-pointer hover:text-red-600 my-2"
                           @click="getRouterToUserUpdate(store.state.user.uid)">
                            个人设置
                        </p>
                        <p @click="logoutFunc" class="cursor-pointer hover:text-red-600 my-2">退出</p>
                    </n-tooltip>
                </div>
                <div class="not-login" v-show="!store.state.user.isLogin">
                    未登录,请<p class="login-text-style" @click="isLoginDialog">登录</p>
                </div>
            </div>
        </div>
    </div>
    <!--    第二行导航栏-->
    <div class="navigation-bar-second">
        <div class="base navigation-bar-second-context">
            <div class="second-bar-context" v-for="(key, value) in barDataList.secondBarNameAndUrl"
                 @click="getRouterToOther(key, value)"
                 :key="value"
                 :class="{'bar-second-bg-active': isActiveSecondBar(value)}"
                 v-show="$route.path.match(/my/) == null && $route.path.match(/friend/) == null ">
                {{ value }}
            </div>
        </div>
    </div>
    <!--    由于最初设计得不好,所以导航栏登录并不是一个组件,懒得改了-->
    <van-dialog :show="showLoginDialog" title="登录" show-cancel-button @confirm="invokeLogin"
                @cancel="hiddenLoginDialog"
                width="500">
        <div class="login-box">
            <div>
                <van-form>
                    <van-field
                        v-model="phone"
                        name="手机号"
                        label="手机号"
                        placeholder="手机号"
                        :rules="[{ required: true, message: '请填写手机号' }]"
                    />
                    <van-field
                        v-model="password"
                        type="password"
                        name="密码"
                        label="密码"
                        placeholder="密码"
                        :rules="[{ required: true, message: '请填写密码' }]"
                    />
                </van-form>
            </div>
        </div>
        <div v-show="isLoading" class="flex items-center justify-center">
            <van-loading size="24px">加载中...</van-loading>
        </div>
    </van-dialog>
</template>

<script>
import {useRouter} from "vue-router";
import {onMounted, reactive, ref, toRefs} from "vue";
import {useStore} from "vuex";
import {NBadge, NAvatar, NTooltip, useNotification, NInput, NDropdown} from 'naive-ui';
import {login, logout} from "@/network/user";
import {getSearchSuggest, getSearchValue} from "@/network/data/serachValue";
import {getCookie} from "@/network/browser";
import {cookieToJson, fromCode, toCode} from "@/util/cal";
import {delCookie, setCookie} from "@/util/tools";

export default {
    name: "NavigationBar",
    setup() {
        const router = useRouter();
        const store = useStore();
        // 通知组件
        const notification = useNotification();
        let user = reactive({
            phone: '',
            password: ''
        })
        const searchInfo = reactive({
            options: [],
        })
        let searchValue = ref('');
        // 记录导航栏的位置,默认为'发现音乐'
        // eslint-disable-next-line no-unused-vars
        let currentBarName = ref('发现音乐');
        let currentSecondBarName = ref('推荐');
        // 网易云图标rul
        let ImageUrl = require("@/assets/image/home/navigationbar/cloud.jpg");
        // 返回首页
        let getRouterToHome = () => {
            router.push({path: '/'});
        }
        // 导航栏数据
        const barDataList = reactive({
            // 第一行的名字以及点击跳转的url, 因为第二行只有发现音乐有数据，所以分为两行
            firstBarNameAndUrl: {
                '发现音乐': '',
                '我的音乐': 'my/music/playlist',
                '朋友': 'friend',
                '商城': '#',
                '音乐人': '#',
                '下载客户端': 'download',
            },
            secondBarNameAndUrl: {
                '推荐': 'discover',
                '排行榜': 'discover/toplist',
                '歌单': 'discover/playlist',
                '主播电台': 'discover/djradio',
                '歌手': 'discover/artist',
                '新碟上架': 'discover/albums',
            }
        })
        
        // key就是url
        const getRouterToOther = (key, value) => {
            // 判断是第一行导航栏还是第二行导航栏
            if (value in barDataList.secondBarNameAndUrl) {
                currentSecondBarName.value = value;
            } else {
                // 更新当前导航位置
                currentBarName.value = value;
            }
            router.push({
                path: `/${key}`,
            })
        }
        // 判断当前导航栏是否活跃，即当前路由是否与传入的url相对应
        const isActiveBar = (value) => {
            if (currentBarName.value == value) {
                return true;
            } else {
                return false;
            }
        }
        // 判断当前第二行导航栏是否活跃，即当前路由是否与传入的value相对应, 只有发现音乐是活跃的
        const isActiveSecondBar = (value) => {
            if (currentSecondBarName.value == value) {
                return true;
            } else {
                return false;
            }
        }
        // 弹出框登录是否弹出
        let showLoginDialog = ref(false);
        
        // 使用弹出框登录
        const isLoginDialog = () => {
            showLoginDialog.value = true;
        }
        // 隐藏弹出框登录
        const hiddenLoginDialog = () => {
            showLoginDialog.value = false;
        }
        
        // 是否处于加载状态
        let isLoading = ref(false);
        // 真正的登录函数
        const invokeLogin = () => {
            isLoading.value = true;
            login(user).then(res => {
                let cookieInfo = cookieToJson(decodeURIComponent(res.data.cookie));
                // 连接成功
                if (res.status == 200) {
                    // 登录成功
                    if (res.data.code == 200) {
                        store.commit('setLoginStatus', true);
                        store.commit('setAvatarUrl', res.data.profile.avatarUrl);
                        store.commit('setNickName', res.data.profile.nickname);
                        store.commit('setUid', res.data.profile.userId);
                        setCookie('cloud_phone', user.phone, cookieInfo[" Expires"]);
                        setCookie('cloud_pwd', toCode(user.password), cookieInfo[" Expires"]);
                        setCookie('MUSIC_U', cookieInfo.MUSIC_U, cookieInfo[" Expires"]);
                        setCookie('__csrf', cookieInfo.__csrf, cookieInfo[" Expires"]);
                        setCookie('__remember_me', cookieInfo.__remember_me, cookieInfo[" Expires"]);
                        showLoginDialog.value = false;
                        notification['success']({
                            content: '登录成功',
                            meta: '听点音乐?'
                        })
                    } else {
                        showLoginDialog.value = false;
                        notification['error']({
                            content: '用户信息错误',
                            meta: '要不再试一次?'
                        })
                    }
                } else {
                    showLoginDialog.value = false;
                    notification['error']({
                        content: '连接服务器失败',
                        meta: '要不再试一次?'
                    })
                }
            })
            
            isLoading.value = false;
        }
        const init = () => {
            let timestamp = new Date().getTime();
            // 如果存在cookie，后台自动登录
            if (store.state.user.isLogin == true) {
                login({phone: getCookie('cloud_phone'), password: fromCode(getCookie(`cloud_pwd`))}).then(res => {
                    if (!res.data.profile) {
                        store.commit('setLoginStatus', false);
                        notification['warning']({
                            content: 'API借口请求成功但是返回数据为空',
                            meta: '实际上你已经登录存在cookie了'
                        })
                        return null;
                    }
                    store.commit('setUid', res.data.profile.userId);
                    store.commit('setAvatarUrl', res.data.profile.avatarUrl);
                    store.commit('setNickName', res.data.profile.nickname);
                });
            }
        }
        onMounted(() => {
            init();
        })
        // 搜索
        const doSearch = () => {
            getSearchValue(searchValue.value).then(res => {
                router.push({
                    name: 'Search', params: {
                        sv: res.data
                    }
                })
            })
        }
        // 搜索建议触发事件
        const inputChange = () => {
            if (searchValue.value === '') {
                // do nothing
            } else {
                getSearchSuggest(searchValue.value).then(res => {
                    console.log(res);
                    // 置空
                    searchInfo.options = [];
                    let idx = 0;
                    // albums_length 专辑数量
                    let albums = res.data.result.albums || [];
                    let artists = res.data.result.artists || [];
                    let playlists = res.data.result.playlists || [];
                    let songs = res.data.result.songs || [];
                    // 搜索建议专辑
                    for (let item of albums) {
                        console.log(item);
                        let tmp = {};
                        tmp.label = '专辑-' + item.name;
                        tmp.key = item.id;
                        searchInfo.options[idx] = tmp;
                        idx++;
                    }
                    // 搜索建议歌手
                    for (let item of artists) {
                        let tmp = {};
                        tmp.label = '歌手-' + item.name;
                        tmp.key = item.id;
                        searchInfo.options[idx] = tmp;
                        idx++;
                    }
                    // 搜索建议歌单
                    for (let item of playlists) {
                        let tmp = {};
                        tmp.label = '歌单-' + item.name;
                        tmp.key = item.id;
                        searchInfo.options[idx] = tmp;
                        idx++;
                    }
                    // 搜索建议歌单
                    for (let item of songs) {
                        let tmp = {};
                        tmp.label = '歌曲-' + item.name + '-' + item.artists[0].name;
                        tmp.key = item.id;
                        searchInfo.options[idx] = tmp;
                        idx++;
                    }
                })
            }
        }
        
        const handleSelect = (key, object) => {
            console.log(object);
            let labelSplitArr = object.label.split('-');
            searchValue.value = labelSplitArr[1];
            let id = key;
            let ids = key;
            if (labelSplitArr[0] === '歌手') {
                if (id === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/artist', query: {id}});
                }
            } else if (labelSplitArr[0] === '专辑') {
                if (id === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/album', query: {id}});
                }
            } else if (labelSplitArr[0] === '歌单') {
                if (id === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/playlist', query: {id}});
                }
            } else if (labelSplitArr[0] === '歌曲') {
                if (ids === 0) {
                    notification['error']({
                        content: '获取到的资源id错误',
                        meta: '切勿重复点击'
                    })
                } else {
                    router.push({path: '/song', query: {ids}});
                }
            }
        }
        // 退出登录函数
        const logoutFunc = () => {
            logout().then(res => {
                // 恢复未登录数据
                store.commit('setLoginStatus', false);
                store.commit('setUid', -1);
                store.commit('setAvatarUrl', require("@/assets/image/home/defaultAva.svg"));
                store.commit('setNickName', '未登录,请登录');
                delCookie('cloud_phone');
                delCookie('cloud_pwd');
                notification['success']({
                    content: '退出成功',
                    meta: '需登录才能享受完整功能'
                })
            })
        }
        // 跳转到用户主页
        const getRouterToUserHome = (id) => {
            if (id === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
                return;
            } else {
                router.push({path: '/user/home', query: {id}});
            }
        }
        // 跳转到搜索页面
        const getRouterToSearchValue = (keywords) => {
            if (keywords.length === 0) {
                notification['warning']({
                    content: '搜索内容为空',
                    meta: '请输入搜索关键字'
                })
                return;
            } else {
                router.push({path: '/search', query: {keywords}});
            }
        }
        const getRouterToUserUpdate = (id) => {
            if (id === 0) {
                notification['error']({
                    content: '获取到的用户id错误',
                    meta: '切勿重复点击'
                })
                return;
            } else {
                router.push({path: '/user/update', query: {id}});
            }
        }
        return {
            router,
            store,
            searchValue,
            ImageUrl,
            ...toRefs(searchInfo),
            getRouterToHome,
            barDataList,
            getRouterToOther,
            isActiveBar,
            isActiveSecondBar,
            ...toRefs(user),
            showLoginDialog,
            isLoginDialog,
            invokeLogin,
            isLoading,
            hiddenLoginDialog,
            doSearch,
            logoutFunc,
            getRouterToUserHome,
            inputChange,
            handleSelect,
            getRouterToSearchValue,
            getRouterToUserUpdate
        }
    },
    components: {
        NBadge,
        NAvatar,
        NTooltip,
        NInput,
        NDropdown
    }
}
</script>

<style lang="scss" scoped>
@import '@/assets/css/base.scss';

.navigation-bar {
    @apply box-border relative;
    width: $client-width;
    z-index: 1000;
    background-color: #242424;
    border-bottom: 1px solid #000;
    
    .navigation-bar-context {
        @apply flex min-w-max;
        .cloud-info {
            @apply flex cursor-pointer my-2 min-w-max;
            .cloud-info-text {
                @apply text-white text-2xl mx-4 my-auto font-bold
            }
        }
        
        .bar-context {
            @apply flex justify-center items-center font-normal cursor-pointer text-white hover:bg-black px-4 ;
            .bottom-triangle {
                @apply mx-auto;
                width: 0px;
                height: 0px;
                border-width: 5px;
                border-style: solid;
                border-color: #000 #000 #C20C0C #000;
            }
        }
        
        .bar-search {
            @apply my-auto rounded mx-32;
        }
        
        .creators-center {
            @apply font-thin my-auto py-1 px-2 text-sm hover:text-white hover:border-white cursor-pointer;
            box-sizing: border-box;
            border: 1px solid #4F4F4F;
            color: #ccc;
            border-radius: 20px;
        }
        
        .user-icon {
            @apply my-auto ml-auto;
            .not-login {
                @apply flex text-white;
                .login-text-style {
                    @apply hover:underline hover:text-blue-300 cursor-pointer;
                    color: #C20C0C;
                }
            }
        }
    }
}

.navigation-bar-second {
    @apply box-border relative;
    width: $client-width;
    z-index: 1001;
    
    background-color: #C20C0C;
    border-bottom: 1px solid #a40011;
    min-height: 5px;
    
    .navigation-bar-second-context {
        @apply flex min-w-max pl-48 ;
        .second-bar-context {
            @apply ml-10 text-white text-xs p-0.5 my-1 rounded-xl px-2 py-0.5 cursor-pointer;
        }
    }
}

.bar-context-bg-active {
    background: black;
}

.bar-second-bg-active {
    background: #9B0909;
}

.login-box {
}
</style>
